package com.sae.vote.controller;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sae.vote.entity.Subject;
import com.sae.vote.entity.Users;
import com.sae.vote.service.SubjectService;
import com.sae.vote.service.UserService;
import com.sae.vote.util.DbUtilsTemplate;

/**
 * 用户相关操作
 * 
 */
@Controller
@RequestMapping
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private SubjectService subjectService;

	/**
	 * 用户发起的投票
	 * 
	 * @param userid
	 *            用户标识
	 * @param request
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/user/{userid}/vote", method = RequestMethod.GET)
	public String myVote(@PathVariable("userid") int userid,
			HttpServletRequest request) throws SQLException {
		// 通过用户查找该用户的投票
		List<Subject> subjects = subjectService.getMySubjectPaged(userid, 0,
				DbUtilsTemplate.PAGE_SIZE);
		request.setAttribute("subjects", subjects);
		if (subjects.size() == DbUtilsTemplate.PAGE_SIZE) {
			request.setAttribute("pos", 2);
		}
		return "user/voteList";
	}

	/**
	 * 同上
	 * 
	 * @param userid
	 * @param pos
	 * @param request
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/user/{userid}/vote/page/{pos}", method = RequestMethod.GET)
	public String myVoteMore(@PathVariable("userid") int userid,
			@PathVariable("pos") int pos, HttpServletRequest request)
			throws SQLException {
		List<Subject> subjects = subjectService.getMySubjectPaged(userid,
				(pos - 1) * DbUtilsTemplate.PAGE_SIZE - 1,
				DbUtilsTemplate.PAGE_SIZE);
		request.setAttribute("subjects", subjects);
		if (subjects.size() == DbUtilsTemplate.PAGE_SIZE) {
			request.setAttribute("pos", pos + 1);
		}
		return "user/voteList2";
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String reg() throws SQLException {
		return "register";
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(@ModelAttribute Users user, HttpSession session, HttpServletRequest request)
			throws SQLException {
		boolean success = userService.register(user);
		if (success) {
			request.setAttribute("r_rst", "ok");
		} else {
			request.setAttribute("r_rst", "fail");
		}
		return "register";
	}
}
